package com.example.test.threadtest;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyBlockingQueue<E> {

    int size;

    LinkedList<E> list = new LinkedList<>();

    private  Lock lock = new ReentrantLock();

    Condition notFull = lock.newCondition();//队列满时的等待条件
    Condition notEmpty = lock.newCondition();//队列空时的等待条件

    public MyBlockingQueue(int size){
        this.size = size;
    }

    public void enqueue(E e) throws InterruptedException{
        lock.lock();
        try {
            while(list.size() == size)
             notFull.await();

            list.add(e);
            System.out.println("进入队列:"+e);
            notEmpty.signal();
        } finally {
             lock.unlock();
        }
    }


    public E dequeue() throws  InterruptedException{
        E e;
        lock.lock();
        try{
            while (list.size() == 0)
                notEmpty.await();
            e = list.removeFirst();

            System.out.println("出队:"+e);

            notFull.signal();

            return e;

        }finally {
            lock.unlock();
        }

    }


    public static void main(String[] args) {

    }

}
